package prob3;

import com.sun.javafx.collections.MappingChange;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.stage.FileChooser;

import javax.xml.bind.JAXB;
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Controller {

    @FXML
    private Button btn;

    @FXML
    private TextArea textarea;

    @FXML
    void btnpressed(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open .txt File");
        fileChooser.setInitialDirectory(new File("./src/prob3"));
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("txt文件", "*.txt"));
        File file=fileChooser.showOpenDialog(btn.getParent().getScene().getWindow());
        List<String> container=new ArrayList<String>();
        try(Scanner scanner=new Scanner(file)) {
            int cntline=1;
            while (scanner.hasNextLine())
            {
                textarea.appendText("Line:"+cntline+' ');
                Pattern pattern=Pattern.compile("[a-zA-Z]+");
                Matcher matcher=pattern.matcher(scanner.nextLine());
                while (matcher.find())
                {
                    container.add(matcher.group().toLowerCase());
                }
                Map<String,Long> duplicates_word =  container.stream().collect(Collectors.groupingBy(String::toString,Collectors.counting()));
                for (String key :
                        duplicates_word.keySet()) {
                    if (duplicates_word.get(key) > 1)
                    {
                        textarea.appendText(key+' '+duplicates_word.get(key).toString()+' ');
                    }
                }
                textarea.appendText("\n");
                cntline++;
            }
        } catch (FileNotFoundException e) {

        }
    }
}
